package com.gfxy.controller;

import com.gfxy.service.IUserService;
import com.gfxy.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    IUserService userService;


    @PostMapping("/login")
    public String login(User user, BindingResult result, HttpServletRequest request, HttpServletResponse response){
        int res = userService.loginUser(user);
        if(res>0){
            request.getSession().setAttribute("user", user);
            return "redirect:/index";
        }else {
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('账号或密码错误!');window.location.href='login.jsp'</script>");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    }

    //用户注册
    @RequestMapping("/regist")
    public String regist(@Valid User user, BindingResult result, HttpServletRequest request, HttpServletResponse response){
        if(result.getAllErrors().size()>0){
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('注册信息不能为空!');window.location.href='register.jsp'</script>");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        }


        int res = userService.registerUser(user);
        if(res > 0){
            request.getSession().setAttribute("user", user);
            return "redirect:/index";
        }
        return "redirect:/register.jsp";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        return "redirect:/login.jsp";
    }
}
